package com.jady.main;

import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.IncompatibleThreadStateException;
import com.sun.jdi.LocalVariable;
import com.sun.jdi.Method;
import com.sun.jdi.StackFrame;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.event.Event;
import com.sun.jdi.event.EventSet;
import com.sun.jdi.event.MethodEntryEvent;
import com.sun.jdi.event.VMDeathEvent;
import com.sun.jdi.event.VMDisconnectEvent;

public class EventHandlerThread implements Runnable{

	LinkedBlockingQueue<EventSet> eventSetsQeue;
	
	

	public EventHandlerThread(LinkedBlockingQueue<EventSet> eventSetsQeue) {
		super();
		this.eventSetsQeue = eventSetsQeue;
	}

	@Override
	public void run() {
		System.out.println("EventHanderThread STARTED.....");
		StringBuffer outBuf = null;
		//try{
		while (true) {
			EventSet eventSet=null;
			try {
				eventSet = eventSetsQeue.take();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}

			for (Event event : eventSet) {
				if (event instanceof VMDeathEvent
						|| event instanceof VMDisconnectEvent) {
					// exit
					return;
				} else if (event instanceof MethodEntryEvent) {
					outBuf = new StringBuffer();
					MethodEntryEvent method = (MethodEntryEvent) event;
					ThreadReference thread = method.thread();
					Method method2 = method.method();

					if (!method2.isConstructor()) { // method2.name().equals("main")
						
						try {
							List<LocalVariable> names = method2.arguments();
							outBuf.append(method2.location()).append("|").append(method2.name());
//
//							List<StackFrame> frames = thread.frames();
//							for (StackFrame stackFrame : frames) { // printing the stack
//																	// of at the
//																	// breakpoint
//								outBuf.append("\nFrameToString:")
//										.append(stackFrame.location()).append("|"
//										+ stackFrame.location().sourcePath());
//							}
						} catch (AbsentInformationException e) {
							e.printStackTrace();
						}
						// for (LocalVariable var : names) {
						// outBuf.append("|Param " + var.name());
						// }
//						catch (IncompatibleThreadStateException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}

						System.out.println(outBuf);
					}

					// if (method2.isConstructor()) {
					// List<String> names = method2.argumentTypeNames();
					// System.out.println("Name: "
					// + method2.getClass().getName() + ":"
					// + method2.name());
					// for (String string : names) {
					// System.out.println("Parem: " + string);
					// }
					// }
				}
			}
		}
		//System.out.println("EventHanderThread COMPLETED.....");
		//eventSet.resume();
		
	}
}
